<template>
<div>
       <!-- 面包屑导航区域 -->
           <el-breadcrumb separator-class="el-icon-arrow-right">
             <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
             <el-breadcrumb-item>权限管理</el-breadcrumb-item>
             <el-breadcrumb-item>角色列表</el-breadcrumb-item>
       </el-breadcrumb>
     <!-- 卡片视图区域 -->
       <el-card>
          <!-- 添加角色按钮区域 -->
         <el-row>
            <el-col>
                <el-button type="primary"></el-button>
            </el-col>
         </el-row>
         <!-- 角色列表区域 -->
           <el-table :data="rolesList" border stripe>
           <!-- 展开列 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                <!-- 一级权限 -->
                  <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbuttom',
i1 === 0 ? 'bdtop' : '', 'vcenter']">
                <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)"> {{item1.authName}}</el-tag>
                <!-- 小箭头图标 -->
             <i class="el-icon-caret-right"></i>
            </el-col>
                 <!-- 渲染二级和三级权限 -->
               <el-col :span="19">
                <!-- 通过v-for 循环二级和三级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id"
                :class="[i2 === 0 ? '' : 'bdtop','vcenter']">
                   <el-col :span="6">
                      <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>

                      <i class="el-icon-caret-right"></i>
                  </el-col>
              <!-- 三级权限 -->
                 <el-col :span="18">
                     <el-tag type="warning" v-for="(item3) in item2.children"
            :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                 </el-col>
                </el-row>
             </el-col>
                 </el-row>
              </template>
            </el-table-column>
            <!-- 索引列 -->
           <el-table-column type="index"></el-table-column>
             <el-table-column label="角色名称" prop="roleName"></el-table-column>
              <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
             <el-table-column label="操作" >
               <!-- 作用域插槽 -->
                <template slot-scope="scope">
                     <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                     <el-button type="danger" icon="el-icon-edit" size="mini">删除</el-button>
                     <el-button type="warning" icon="el-icon-edit" size="mini"
               @click="showSetRightDialog(scope.row)" >分配权限</el-button>
               </template>

            </el-table-column>
         </el-table>
    <!-- 分配权限对话框 -->
      <el-dialog
      title="分配权限"
     :visible.sync="setRightDialogVisible"
     width="50%" @close="setRightDialogClosed">
    <el-tree :data="rightlist" :props="treeProps" show-checkbox node-key="id" default-expand-all
 :default-checked-keys="treeKeys" ref="treeRef"></el-tree>
     <span slot="footer" class="dialog-footer">
       <el-button @click="setRightDialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="allotRight">确 定</el-button>
     </span>
    </el-dialog>
       </el-card>
</div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表
      rolesList: [],
      // 分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限列表
      rightlist: [],
      // 树形结构属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 所有默认勾选的id数组
      treeKeys: [],
      // 当前即将被分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表数据
    async  getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表！')
      }
      this.rolesList = res.data
      console.log()
    },
    // 根据Id删除对应权限
    async removeRightById (role, rightId) {
      // 提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消本次删除操作！')
      }
      // console.log('确认删除')
      // 发起请求删除角色对应的权限
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败！')
      }
      // this.getRoleList
      role.children = res.data
      this.$message.success('删除角色成功!')
    },
    // 展示分配权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.rightlist = res.data

      this.getLeafKeys(role, this.treeKeys)

      this.setRightDialogVisible = true
    },
    // 获取所有三级权限id
    getLeafKeys (node, arr) {
      // 先该节点是否为三级节点
      // 只需要通过判断该节点是否包含children属性
      if (!node.children) {
        return arr.push(node.id)
      }
      //
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框关闭事件
    setRightDialogClosed () {
      this.treeKeys = []
    },
    // 点击确定按钮分配角色
    async  allotRight () {
    // 获取所有勾选的key
      const keys = [
      // 拿到所有勾选的id数组
        ...this.$refs.treeRef.getCheckedKeys(),
        // 拿到半勾选的id数组
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 转化成一逗号分隔的字符串
      const idStr = keys.join(',')

      const { data: res } = await this.$http.push(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功！')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
   .el-tag{
      margin: 7px;
   }
   .bdtop{
       border-top: 1px solid #EEEEEE;
   }
   .bdbuttom{
       border-top: 1px solid #EEEEEE;
   }
   .vcenter{
      display: flex;
       align-items: center;
   }
</style>
